<template>
  <el-container>
    <el-main>
      <div class="default-main ba-table-box">
        <TableHeader
          :buttons="['refresh', 'comSearch', 'columnDisplay']"
          :quick-search-placeholder="placeholder"
          @action="baTable.onTableHeaderAction"
        />
        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" @action="baTable.onTableAction" />
        <!-- 料号详情 -->
        <More
          ref="moreRef"
          v-if="MasterPlan.showMoreForm"
          v-model="MasterPlan.showMoreForm"
        />
      </div>
    </el-main>
  </el-container>
</template>
<script lang="ts" setup>
import _ from "lodash";
import { ref, provide, onMounted, markRaw } from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff, DictOperation } from "@/utils/common"; // 导入表格api方法生成器
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { BoardCurrentMain } from "@/api/backend/index";
import { useRoute, useRouter } from "vue-router";
import { useNavTabs } from "@/store/navTabs";
import { useAssetGateway } from "@/store/backend/Assets/gateway";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useAssetSite } from "@/store/backend/Assets/site";
import { useBoardProcessPull } from "@/store/backend/Board/processPull";
import { useDept } from "@/store/backend/SysM/dept";
import { useUser } from "@/store/backend/SysM/user";
import Click from "./components/click.vue";
import type { FormInstance } from "element-plus";
import { useFollowProlem } from "@/store/backend/Board/followProlem";
import { useBoardMasterPlan } from "@/store/backend/Board/MasterPlan";
import More from "./components/more.vue";
import { useBuddyGoods } from "@/store/backend/BomM/goods";
import CustNameSearch from "./components/searchTags/custName.vue";
import NewProSearch from "./components/searchTags/newPro.vue";
import GoodsSearch from "./components/searchTags/goods.vue";
import TagSearch from "@/components/tagSearch/index.vue";

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const route = useRoute();
const router = useRouter();
const navTabs = useNavTabs();
const gateway = useAssetGateway();
const dictionary = useDictionary();
const site = useAssetSite();
const dept = useDept();
const user = useUser();
const goods = useBuddyGoods();
const processPull = useBoardProcessPull();
const followProlem = useFollowProlem();
const MasterPlan = useBoardMasterPlan();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + BoardCurrentMain)
      ? (navTabs as any).pageSizeMap.get(route.path + BoardCurrentMain)
      : 10;
  }
  return 50;
};

//初始化字典处理类
const dictOperation = new DictOperation();

//获取字典
const getDictionary = () => {
  //获取问题域的字典
  // dictOperation.getDictionary(
  //   followProlem,
  //   "sys_problem_area",
  //   "proCate",
  //   "type"
  // );
};
// getDictionary();

//全局事件总线
const { proxy } = useCurrentInstance();
const baTable = new baTableClass(
  new baTableApi(BoardCurrentMain), //this.api = api菜单管理相关
  {
    pk: "id",
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("goodsNo"),
        label: "料号",
        prop: "goodsNo",
        align: "center",
        fixed: "left",
        width: 130,
        operatorPlaceholder: "精确搜索",
        render: "customRender",
        customRender: markRaw(Click),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(GoodsSearch),
      },
      {
        show: filedShowOff("reqDate"),
        label: "首工序欠量日期",
        prop: "reqDate",
        align: "center",
        fixed: "left",
        width: 130,
        operator: false,
      },
      {
        show: filedShowOff("fNeeded"),
        label: "首工序欠量",
        prop: "fNeeded",
        align: "center",
        fixed: "left",
        width: 110,
        operator: false,
      },
      {
        show: filedShowOff("stockLess"),
        label: "需求超库存量",
        prop: "stockLess",
        align: "center",
        width: 110,
        operator: false,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          if (value == "-") {
            return "<p>" + value + "</p>";
          } else if (!value) {
            return "<p>" + "-" + "</p>";
          }
          return "<p>" + (value - 0).toFixed(0) + "</p>";
        },
      },
      {
        show: filedShowOff("inprocessQty"),
        label: "在途工单数",
        prop: "inprocessQty",
        align: "center",
        width: 110,
        operator: false,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          if (value == "-") {
            return "<p>" + value + "</p>";
          } else if (!value) {
            return "<p>" + "-" + "</p>";
          }
          return "<p>" + (value - 0).toFixed(0) + "</p>";
        },
      },
      {
        show: filedShowOff("newPro"),
        label: "首工序",
        prop: "newPro",
        align: "center",
        width: 120,
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(NewProSearch),
      },
      {
        show: filedShowOff("mtype"),
        label: "机型",
        prop: "mtype",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("firstProSche"),
        label: "首工序推荐交期",
        prop: "firstProSche",
        align: "center",
        width: 150,
        sortable: "custom",
        operator: false,
      },
      {
        show: filedShowOff("maReqDay"),
        label: "原材料需求日期",
        prop: "maReqDay",
        align: "center",
        width: 125,
        operator: false,
      },
      {
        show: filedShowOff("maPurDay"),
        label: "原材料采购日期",
        prop: "maPurDay",
        align: "center",
        width: 125,
        operator: false,
      },
      // {
      //   show: filedShowOff("recMainQty"),
      //   label: "推荐主计划",
      //   prop: "recMainQty",
      //   align: "center",
      //   width: 100,
      //   operator: false,
      // },
      {
        show: filedShowOff("greatest"),
        label: "推荐主计划量",
        prop: "greatest",
        align: "center",
        operator: false,
        width: 140,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          if (value == "-") {
            return "<p>" + value + "</p>";
          } else if (!value) {
            return "<p>" + "-" + "</p>";
          }
          return "<p>" + (value - 0).toFixed(0) + "</p>";
        },
      },
      {
        show: filedShowOff("matReq"),
        label: "主计划材料需求量",
        prop: "matReq",
        align: "center",
        width: 140,
        operator: false,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          if (value == "-") {
            return "<p>" + value + "</p>";
          } else if (!value) {
            return "<p>" + "-" + "</p>";
          }
          return "<p>" + (value - 0).toFixed(0) + "</p>";
        },
      },
      {
        show: filedShowOff("reqStatus"),
        label: "用户需求释放状态",
        prop: "reqStatus",
        align: "center",
        width: 140,
        operator: false,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          if (value == "需求释放不足") {
            return "<p style='color:red'>" + value + "</p>";
          } else if (value == "需求释放充足") {
            return "<p>" + value + "</p>";
          }
          return "<p>" + "-" + "</p>";
        },
      },
      // {
      //   show: filedShowOff("minMoq"),
      //   label: "外协最小起订量",
      //   prop: "minMoq",
      //   align: "center",
      //   width: 130,
      //   operator: false,
      //   render: "customTemplate",
      //   customTemplate: (row: TableRow, field: TableColumn, value: any) => {
      //     return "<p>" + (value - 0).toFixed(0) + "</p>";
      //   },
      // },
      {
        show: filedShowOff("leadTime"),
        label: "建议需求释放期",
        prop: "leadTime",
        align: "center",
        width: 155,
        operator: false,
      },
      {
        show: filedShowOff("custName"),
        label: "客户",
        prop: "custName",
        align: "center",
        width: 150,
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(CustNameSearch),
      },
      {
        show: filedShowOff("minPurQty"),
        label: "最小生产量",
        prop: "minPurQty",
        align: "center",
        width: 110,
        operator: false,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          if (value == "-") {
            return "<p>" + value + "</p>";
          }
          return "<p>" + (value - 0).toFixed(0) + "</p>";
        },
      },
      {
        show: filedShowOff("minMa"),
        label: "原材料最小采购量",
        prop: "minMa",
        align: "center",
        width: 130,
        operator: false,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          if (value == "-") {
            return "<p>" + value + "</p>";
          }
          return "<p>" + (value - 0).toFixed(0) + "</p>";
        },
      },
      {
        show: filedShowOff("minMoq"),
        label: "外协最小起订量",
        prop: "minMoq",
        align: "center",
        width: 110,
        operator: false,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          if (value == "-") {
            return "<p>" + value + "</p>";
          }
          return "<p>" + (value - 0).toFixed(0) + "</p>";
        },
      },
      {
        show: filedShowOff("maStockDay"),
        label: "原材料采购周期",
        prop: "maStockDay",
        align: "center",
        width: 110,
        operator: false,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          if (value == "-") {
            return "<p>" + value + "</p>";
          }
          return "<p>" + (value - 0).toFixed(0) + "</p>";
        },
      },
      {
        show: filedShowOff("prodays"),
        label: "生产提前期",
        prop: "prodays",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("material"),
        label: "原材料号",
        prop: "material",
        align: "center",
        operator: false,
        width: 130,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          return "<p style='color:#409eff;cursor: pointer;'>" + value + "</p>";
        },
      },
      {
        show: filedShowOff("fUnitPic"),
        label: "材料单耗",
        prop: "fUnitPic",
        align: "center",
        width: 110,
        operator: false,
      },
      {
        show: filedShowOff("maType"),
        label: "材料类别",
        prop: "maType",
        align: "center",
        width: 110,
        operator: false,
      },
      {
        show: filedShowOff("maName"),
        label: "原材料",
        prop: "maName",
        align: "center",
        width: 130,
        operator: false,
      },
      {
        show: filedShowOff("maSpec"),
        label: "ma_spec",
        prop: "maSpec",
        align: "center",
        width: 400,
        operator: false,
      },
      {
        show: filedShowOff("maxDeldate"),
        label: "需求释放期",
        prop: "maxDeldate",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("stockDay"),
        label: "外协提前期",
        prop: "stockDay",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("recReqDate"),
        label: "建议需求日期",
        prop: "recReqDate",
        align: "center",
        width: 160,
        operator: false,
      },
      {
        show: filedShowOff("segDays"),
        label: "工序提前期/天",
        prop: "segDays",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("mainReqFlag"),
        label: "是否拉动",
        prop: "mainReqFlag",
        align: "center",
        width: 125,
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show: operatorShowOff([route.path + "/edit", route.path + "/remove"]),
        label: "操作",
        align: "center",
        width: "130",
        render: "buttons",
        fixed: "right",
        operator: false,
        buttons: [
          {
            render: "tipButton",
            name: "more",
            title: "料号详情",
            text: "",
            type: "primary",
            icon: "iconfont icon-chaxunyujisuan",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
      },
    ],
    filter: {
      pageSize: pageSizeKeep(),
    },
    showComSearch: true, //展开通用搜索
    extend: {
      column: true, //是否合并行
      columnFiled: ["goodsNo", "goodReqDate", "crequests"], //该字段相同合并
    },
  },
  {
    // 默认表单数据(添加)
    // defaultItems: {
    //   siteOrder: 1,
    //   siteType: 0, //0为地区类型
    // },
  },
  {
    onSubmit: ({
      formEl,
      operate,
      items,
    }: {
      formEl: FormInstance | undefined;
      operate: string;
      items: anyObj;
    }) => {
      console.log("表单提交前", formEl, operate, items);
      return true;
    },
  }
);

//打开晨会问题跟踪表单
const infoButtonClick = (name: string, row: any) => {
  if (!row) return;
  // 数据来自表格数据,未重新请求api,深克隆,不然可能会影响表格
  let rowClone = _.cloneDeep(row);
  console.log("打开晨会问题跟踪表单row", row);
  baTable.form.extend!["problem"] = rowClone;
  baTable.form.operate = "problem";
  // router.push({ path: "/admin/BoardMasterPlan/iotDetail" });
};
//打开料号详情页表单
const moreButtonClick = (name: string, row: any) => {
  if (!row) return;
  // 数据来自表格数据,未重新请求api,深克隆,不然可能会影响表格
  MasterPlan.single = row;
  router.push({ path: "/admin/BoardMasterPlan/detail" });
};

onMounted(() => {
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(BoardCurrentMain);

  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      if (!baTable.activate) return;
      //回滚功能暂无
      if (data.name == "rollback") {
        // onRollback([data.row[baTable.table.pk!]])
      } else if (data.name == "info") {
        //携带主键字段pk
        // infoButtonClick(
        //   (data.row as TableRow)[baTable.table.pk!],
        //   data.row as any
        // );
      } else if (data.name == "more") {
        //携带主键字段pk
        moreButtonClick(
          (data.row as TableRow)[baTable.table.pk!],
          data.row as any
        );
      }
    }
  );
});

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("gateway", gateway);
provide("dictionary", dictionary);
provide("site", site);
provide("dictOperation", dictOperation);
provide("processPull", processPull);
provide("dept", dept);
provide("user", user);
provide("router", router);
provide("MasterPlan", MasterPlan);
provide("goods", goods);
</script>
<style lang="scss" scoped>
.el-main {
  padding: 0;
}
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}
</style>
